package com.cn.yunhe.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;

public class BaseDao {
	// 数据库驱动程序
	private final String DBDRIVER = "com.mysql.jdbc.Driver";
	// 数据库连接地址
	private final String DBURL = "jdbc:mysql://localhost:3306/mldn";
	// 数据库用户名
	private final String DBUSER = "root";
	// 数据库连接密码
	private final String DBPASSWORD = "211221";
	

	// 声明一个数据库连接对象
	protected Connection conn;
	protected PreparedStatement pstmt;
	protected ResultSet rs;

/**
 *  获取数据库连接对象
 * 
 */
	public Connection getConnection() {
		Connection conn = null;// 连接对象
		// 监控异常代码
		try {
//				Class.forName(DBDRIVER);
//				conn=DriverManager.getConnection(DBURL,DBUSER,DBPASSWORD);
			Context initContext = new InitialContext();
			Context envContext = (Context) initContext.lookup("java:/comp/env");//javaEE默认路径
			DataSource ds = (DataSource) envContext.lookup("jdbc/mysql");//为DataSource的名字
           conn=ds.getConnection();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return conn;
	}

	// 关闭数据库连接
	public void closeAll(Connection conn, Statement stmt, ResultSet rs) {

		if (rs != null) {
			try {
				rs.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (stmt != null) {
			try {
				stmt.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		if (conn != null) {
			try {
				conn.close();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	/**
	 * 
	 * @param sql
	 * @param prams增加更新
	 * @return
	 */
	public int exceuteUpdate(String sql, Object... prams) {
		int result = 0;
		conn = this.getConnection();
		try {
			pstmt = conn.prepareStatement(sql);
			for (int i = 0; i < prams.length; i++) {
				pstmt.setObject(i + 1, prams[i]);
			}
			result = pstmt.executeUpdate();
		} catch (SQLException e) {
			e.printStackTrace();
		} finally {
			closeAll(conn, pstmt, rs);
		}
		return result;
	}

	

};